package com.kabuda.blog.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kabuda.blog.dao.pojo.Admin;
import com.kabuda.blog.dao.pojo.Article;
import com.kabuda.blog.mapper.AdminMapper;
import com.kabuda.blog.mapper.ArticleMapper;
import com.kabuda.blog.service.*;
import com.kabuda.blog.utils.JWTUtils;
import com.kabuda.blog.vo.ArticleVo;
import com.kabuda.blog.vo.Result;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import springfox.documentation.spring.web.json.Json;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author kabuda
 * @create 2023-04-04 17:5I
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Result login(Admin admin) {
        //校验有效性
        String password = admin.getPassword();
        password = Md5Crypt.md5Crypt(password.getBytes(StandardCharsets.UTF_8), UserServiceImpl.salt);
        String username = admin.getUsername();
        if (!StringUtils.isNotEmpty(username) || !StringUtils.isNotEmpty(password)) {
            return Result.fail(100, "账号或者密码为空");
        }
        //检查数据库是否存在该用户
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        wrapper.eq("password", password);
        Admin one = this.getOne(wrapper);
        if (one == null) {
            return Result.fail(101, "用户或者密码输入错误");
        }

        String token = JWTUtils.createToken(one.getId());

        redisTemplate.opsForValue().set("TOKEN_ADMIN_" + token, JSON.toJSONString(one), 1, TimeUnit.DAYS);

        return Result.success(token);
    }

    @Override
    public Result getInfo(String token) {
        String one= redisTemplate.opsForValue().get("TOKEN_ADMIN_" + token);
        Admin admin = JSON.parseObject(one, Admin.class);
        return Result.success(admin);
    }

    @Override
    public Result logout(String token) {
       redisTemplate.delete("TOKEN_ADMIN_" + token);
        return Result.success(null);
    }
}
